package com.rtx.wms.std.handler.transfer.finsh;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.transer.bean.ApiTransferDetailFinish;
import com.rtx.wms.std.transer.bean.ApiTransferFinish;
import com.rtx.wms.std.transer.bean.Transfer;
import com.rtx.wms.std.transer.bean.TransferDetail;
import com.rtx.wms.std.transer.service.ApiTransferFinishService;
import com.rtx.wms.std.transer.service.TransferService;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Component
public class TransferFinishHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TransferService transferService;

    @Autowired
    private ApiTransferFinishService apiTransferFinishService;

    /**
     * 处理完成的出库单
     * @param whseid
     */
    public void handlerOrdersFinish(String whseid){
        //获取待回传的出库单
        List<Transfer> list = selectfinish(whseid);
        for(Transfer o : list){
            //写入回传中间表
            addfinish("ris_edi",o);
            //更新状态
            updateStatus(whseid,o);
        }
    }

    /**
     * 写入回传中间表
     * @param whseid
     * @param o
     */
    private void addfinish(String whseid, Transfer o) {
        try {
            ApiTransferFinish finish = convertApiTransfer(o);
            
            apiTransferFinishService.insertTransferAndDetailFinish(whseid, finish);
            
            o.setRtxeditflagErp(WmsConstant.SUCCESS_FLAG);
        } catch (Exception e) {
            logger.error("仓库-{}-{}写入回传中间表异常",whseid,o.getRtxeditflagErp(),e);
            o.setRtxeditflagErp(WmsConstant.FAIL_FLAG);
            o.setRtxeditflagMsg(e.getMessage());
        }
    }

    /**
     * 转化类型
     * @param o
     * @return
     */
    private ApiTransferFinish convertApiTransfer(Transfer o) {
    	//获取唯一编号
    	String batchid = IdUtil.getSnowflakeNextIdStr();
    	ApiTransferFinish finish = new ApiTransferFinish();
    	BeanUtils.copyProperties(o,finish);
    	finish.setRtxqueue(0);
    	finish.setEdiflag("P");
    	finish.setGenerateisHicharges(o.getGenerateisHicharges());
    	finish.setForteFlag(o.getForteFlag());

    	List<ApiTransferDetailFinish> details = new ArrayList<>();
    	for(TransferDetail od : o.getDetails()){
    		ApiTransferDetailFinish detail = new ApiTransferDetailFinish();
    		BeanUtils.copyProperties(od,detail);
    		try {
    			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    			detail.setFromlottable04(df.format(od.getFromlottable04()));
    			detail.setFromlottable05(df.format(od.getFromlottable05()));
			} catch (Exception e) {
			}
    		
    		detail.setBatchid(batchid);
    		details.add(detail);
    	}

    	finish.setBatchid(batchid);
    	finish.setDetails(details);
    	return finish;
    }

    
    /**
     * 更新出库单
     * @param whseid
     * @param o
     */
    private void updateStatus(String whseid, Transfer o) {
        LambdaUpdateWrapper<Transfer> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(Transfer::getTransferkey,o.getTransferkey())
                .set(Transfer::getRtxeditflagErp,o.getRtxeditflagErp())
                .set(Transfer::getRtxeditflagMsg, StrUtil.sub(o.getRtxeditflagMsg(),0,499));
        transferService.updStatus(whseid,wrapper);
    }

    /**
     * 查询需要回传上位出库单
     * @param whseid
     * @return
     */
    public List<Transfer> selectfinish(String whseid){
    	LambdaUpdateWrapper<Transfer> qw = Wrappers.lambdaUpdate();
    	qw.eq(Transfer::getStatus, "9");
    	qw.eq(Transfer::getToexamine, "0");
    	qw.eq(Transfer::getRtxeditflagErp, WmsConstant.DEFAULT_FLAG);
        return transferService.queryWithDetailByCondition(whseid, qw);
    }
}
